/** biome-ignore-all lint/performance/noImgElement: This is a valid use case */
"use client";

import { Spinner } from "@/components/ui/spinner";
import {
  BASE_HEIGHT,
  BASE_WIDTH_PERCENTAGE,
} from "@/hooks/presentation/useRootImageActions";
import { cn } from "@/lib/utils";
import { usePresentationState } from "@/states/presentation-state";
import ImagePlaceholder from "../image-placeholder";
import { type RootImageProps } from "../root-image";

export default function RootImageStatic({
  image,
  layoutType,
  slideId,
}: Omit<RootImageProps, "slideIndex">) {
  const { rootImageGeneration } = usePresentationState();
  const computedGen = slideId ? rootImageGeneration[slideId] : undefined;
  const cropSettings = image.cropSettings || {
    objectFit: "cover" as const,
    objectPosition: { x: 50, y: 50 },
  };

  const imageStyles: React.CSSProperties = {
    objectFit: cropSettings.objectFit,
    objectPosition: `${cropSettings.objectPosition.x}% ${cropSettings.objectPosition.y}%`,
    transform: `scale(${cropSettings.zoom ?? 1})`,
    transformOrigin: `${cropSettings.objectPosition.x}% ${cropSettings.objectPosition.y}%`,
    height: "100%",
    width: "100%",
    display: "block",
  };

  const sizeStyle: React.CSSProperties = (() => {
    const hasExplicitHeight = Boolean(image.size?.h);
    const hasExplicitWidth = Boolean(image.size?.w);
    if (!hasExplicitHeight && !hasExplicitWidth) {
      if (layoutType === "vertical") {
        return { height: BASE_HEIGHT, width: "100%" } as const;
      }
      return { width: BASE_WIDTH_PERCENTAGE } as const;
    }
    if (layoutType === "vertical") {
      return { height: image.size?.h, width: "100%" } as const;
    }
    return { width: image.size?.w } as const;
  })();

  // Root image is now generated by PresentationGenerationManager

  return (
    <div className={cn("relative shrink-0")} style={sizeStyle}>
      <div className="h-full overflow-hidden border bg-background/80 shadow-md backdrop-blur-sm">
        {computedGen?.status === "pending" ? (
          <div className="flex h-full flex-col items-center justify-center bg-muted/30 p-4">
            <Spinner className="mb-2 h-8 w-8" />
            <p className="text-sm text-muted-foreground">
              Generating image for &quot;{image.query}&quot;...
            </p>
          </div>
        ) : (
          <div className="relative h-full" tabIndex={0}>
            {(computedGen?.status === "success" && computedGen.url) ||
            image.url ? (
              <img
                src={
                  (computedGen?.status === "success" && computedGen.url) ||
                  image.url
                }
                alt={image.query}
                style={imageStyles}
              />
            ) : (
              <ImagePlaceholder isStatic={true} className="h-full" />
            )}
          </div>
        )}
      </div>
    </div>
  );
}
